package com.qf.fmall2203.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2203.category.entity.Category;
import com.qf.fmall2203.category.mapper.CategoryMapper;
import com.qf.fmall2203.category.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2203.introducepro.entity.Product;
import com.qf.fmall2203.introducepro.entity.ProductImg;
import com.qf.fmall2203.introducepro.service.IProductImgService;
import com.qf.fmall2203.introducepro.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2023-02-14
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    IProductService productService;

    @Autowired
    IProductImgService productImgService;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> categoryList() {

        // 查询所有一级分类信息
        final List<Category> firstCategoryList = list(new QueryWrapper<Category>().eq("parent_id", 0));

        // 遍历所有查询到的一级分类，填充二级分类数据
        for (Category category : firstCategoryList) {

            // 获取当前一级分类ID
            final Integer categoryId = category.getCategoryId();

            // 查询当前ID下有哪些二级分类
            final List<Category> secondCateoryList = list(new QueryWrapper<Category>().eq("parent_id", categoryId));

            // 遍历 secondCateoryList ，为每个二级分类对象填充 三级分类 数据
            for (Category sec : secondCateoryList) {
                // 获取二级分类ID
                final Integer secId = sec.getCategoryId();
                final List<Category> thirdCategoryList = list(new QueryWrapper<Category>().eq("parent_id", secId));

                // 把三级分类信息设置到二级分类对象中
                sec.setCategories(thirdCategoryList);
            }

            // 把查询出来的二级分类，设置到一级分类对象中
            category.setCategories(secondCateoryList);

        }

        return firstCategoryList;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> categoryListBySql() {

        final CategoryMapper mapper = this.getBaseMapper();

        return mapper.listCategoryList();

    }

    @Override
    public List<Category> getCategoryRecommend() {

        List<Category> categoryList = list(new QueryWrapper<Category>().eq("parent_id", 0));

        for (Category category : categoryList) {
            Integer categoryId = category.getCategoryId();

            List<Product> productList = productService.list(new QueryWrapper<Product>().
                    eq("root_category_id", categoryId).orderByDesc("sold_num").last("limit 6"));

            for (Product product : productList) {
                String productId = product.getProductId();

                List<ProductImg> imgList = productImgService.list(new QueryWrapper<ProductImg>().eq("item_id", productId));
                product.setImgs(imgList);
            }
            category.setProducts(productList);

        }


        return categoryList;
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Category> categorylistRecursive() {

        //查询全部分类信息
        List<Category> all = list();

        //通过stream流的filter方法获取顶级分类数据
        List<Category> first = all.stream().filter(category -> category.getParentId().equals(0)).collect(Collectors.toList());

        //给当前分类信息填充下级分类信息
        populateChild(first,all);

        //给一级分类对象填充下属的二级分类信息

       /*
*/
        return first;
    }



    private void populateChild(List<Category> list, List<Category> all) {

        for (Category category : list) {

            Integer categoryId = category.getCategoryId();

            List<Category> child = all.stream().filter(c -> c.getParentId().equals(categoryId)).collect(Collectors.toList());

            if(child!=null && child.size()>0){
                populateChild(child, all);
            }

            category.setCategories(child);
        }
    }

    @Override
    public List<Category> categorylistRecursiveBetter() {

        //查询全部分类信息
        List<Category> all = list();

        //构建一个map结构 key=parentId value= List<Category>

      /*  Map<Integer, List<Category>> map = all.stream().collect(Collectors.groupingBy(new Function<Category, Integer>() {
            @Override
            public Integer apply(Category category) {
                return category.getParentId();
            }
        }));*/

        Map<Integer, List<Category>> map = all.stream().collect(Collectors.groupingBy(Category::getParentId));

        //获取顶级分类

        List<Category> list = map.get(0);

        populateBetter(list,map);

        return list;
    }

    private void populateBetter(List<Category> list, Map<Integer, List<Category>> map) {

        for (Category category : list) {

            Integer categoryId = category.getCategoryId();
            List<Category> child = map.get(categoryId);

            if(child!=null&&child.size()>0){
                populateBetter(child,map);
                category.setCategories(child);
            }else {
                //当没有下级分类的数据时，创建一个长度为0的list，避免遍历数据时出现空指针异常，也确保前端拿到的json中是[]
                category.setCategories(new ArrayList<>());

            }

        }

    }
}
